package com.ccb.sc.common.modules.member.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedisBetterConfigImpl;
import com.ccb.sc.common.modules.setting.service.ISettingsService;
import com.ccb.sc.common.modules.setting.vo.WxMaSettingBo;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.common.redis.WxRedisOps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author ken
 * @version 1.0
 * @date 2022-07-29
 */
@Service
public class MaService {

    private ISettingsService settingsService;

    private StringRedisTemplate stringRedisTemplate;

    private WxMaConfig maConfig() {
        WxMaSettingBo settings = settingsService.getSettings(WxMaSettingBo.class);
        WxRedisOps wxRedisOps = new RedisTemplateWxRedisOps(stringRedisTemplate);
        WxMaRedisBetterConfigImpl config = new WxMaRedisBetterConfigImpl(wxRedisOps, "app:wx");
        config.setAppid(settings.getAppid());
        config.setSecret(settings.getSecret());
        config.setToken(settings.getToken());
        config.setAesKey(settings.getAesKey());
        config.setMsgDataFormat(settings.getMsgDataFormat());
        return config;
    }

    public WxMaService getWxMaService() {
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(maConfig());
        return service;
    }


    @Autowired
    @Lazy
    public void setSettingsService(ISettingsService settingsService) {
        this.settingsService = settingsService;
    }

    @Autowired
    @Lazy
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
}
